package com.djx.business.access.service.impl;

import com.djx.business.access.repository.UserRepository;
import com.djx.business.access.service.UserService;
import com.djx.commons.uitls.IdWorker;
import com.djx.commons.constants.Constants;
import com.djx.commons.response.Result;
import com.djx.commons.response.ResultCode;
import com.djx.entity.access.User;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 2021年1月9日
     * 敦佳星
     * 查询用户信息
     * <p>
     * 有参根据参数查询 无参查询全部
     *
     * @param map
     * @return
     */
    @Override
    public List<User> findUser(Map<String, Object> map) {
        String nickName = (String) map.get("nickName");

        return userRepository.findByLikeUsername(nickName);
    }

    /**
     * 根据用户名和密码查询当前用户
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public User findByUsernameAndPassword(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password);
    }

    /**
     * 添加用户
     *
     * @param map
     * @return
     */
    @Override
    public Result addUser(Map<String, Object> map) {

        User username = userRepository.findByUsername(map.get("username").toString());

        System.out.println("username  ::: "+username);
        if (null != username) {
            return new Result(ResultCode.ADD_FAILONE);
        }

        User user = new User();
        user.setId(new IdWorker().nextId() + "");
        user.setUsername(map.get("username").toString());
        user.setPassword(new Md5Hash("123", map.get("username").toString(), 3).toString());
        user.setUserLevel(Constants.admin);
        user.setIsDelete(Constants.noDelete);
        user.setModifyTime(new Date());
        try {
            userRepository.save(user);
            return new Result(ResultCode.ADD_SUCCESS);

        } catch (Exception e) {

            return new Result(ResultCode.ADD_FAIL);
        }

    }

    /**
     * 根据用户名查询信息
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        User byUsername = userRepository.findByUsername(username);
        return byUsername;
    }


}
